package com.fy.core.util;

import cn.hutool.json.JSONUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.fy.sys.entity.User;

import java.util.Calendar;
import java.util.Date;

/**
 * @author hxd
 * @version 1.0
 * @ClassName JWTUtil
 * @date 2023/6/15 21:12
 * @since 1.0
 */
public class JWTUtil {
    private static final String salt="qf";
    public static String generatorMinutesToken(Object user,Integer expire){
        Calendar instance = Calendar.getInstance();
        instance.setTime(new Date());
        instance.add(Calendar.MINUTE,expire);

        //颁发jwt令牌
        String token = JWT.create()
                //指定头部（可默认）
                //withHeader
                //指定payload
                .withClaim("user", JSONUtil.toJsonStr(user))
                //指定过期时间
                .withExpiresAt(instance.getTime())
                //签名
                .sign(Algorithm.HMAC256(salt));
        return token;
    }

    public static String generatorHoursToken(Object user,Integer expire){
        Calendar instance = Calendar.getInstance();
        instance.setTime(new Date());
        instance.add(Calendar.HOUR,expire);

        //颁发jwt令牌
        String token = JWT.create()
                //指定头部（可默认）
                //withHeader
                //指定payload
                .withClaim("user", JSONUtil.toJsonStr(user))
                //指定过期时间
                .withExpiresAt(instance.getTime())
                //签名
                .sign(Algorithm.HMAC256(salt));
        return token;
    }

    /**
     * 校验令牌
     * @return
     */
    public static User verifyToken(String token){
        try {
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256("qf")).build();
            DecodedJWT verify = jwtVerifier.verify(token);
            String userJson = verify.getClaim("user").asString();
            User user = JSONUtil.toBean(userJson, User.class);
            return user;
        } catch (Exception e) {
            return null;
        }
    }
}
